// packageB/pages/addBaojia/addBaojia.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    listLenght: false,
    moude: {
      id: 0,
      productnamevalue: '', //输入品名
      specificationvalue: '', //输入规格
      selectProductname: '', //选择推荐的品名
      selectSpecification: '', //选择推荐的规格
      productnamelength: 0, //品名长度
      specificationlength: 0, //品名长度
      productnamemaxlength: 25, //输入最大长度
      specificationmaxlength: 25, //输入最大长度
      productnameList: [], //品名推荐标签
      specificationList: [],
      productnameListIndex: -1, //选品名下表
      specificationListIndex: -1, //选规格下表
      maxprice: '',
      minprice: '',
      unit: ''
    },
    list: [],


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options)
    let that = this
    this.setData({
      classid: options.classid,
      unit: options.unit
    })
    const eventChannel = this.getOpenerEventChannel()
    // 监听 acceptDataFromOpenerPage 事件，获取上一页面通过 eventChannel 传送到当前页面的数据
    eventChannel.on('acceptDataFromOpenerPage', async function (data) {
      console.log(data)
      that.setData({
        dataTempList: data
      })
      await that.queryPInmingBytype(options.classid, options.unit)

    })
    // let a = this.data.list,
    //   b = this.data.moude
    // a.push(JSON.parse(JSON.stringify(b)))
    // this.setData({
    //   list: a,
    //   classid:options.classid
    // },()=>{
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 添加
  clickAddMoude(e) {
    let a = this.data.list,
      b = this.data.moude
    if (a.length >= 5) {
      wx.showToast({
        title: '最多只能添加5个',
      })
      return
    } else {
      a.push(JSON.parse(JSON.stringify(b)))
      this.setData({
        list: a,
        listLenght: true
      })
    }
  },
  // 删除大类
  jianMoude(e) {
    let index = e.currentTarget.dataset.index,
      list = this.data.list
    if (list.length == 1) {
      this.setData({
        listLenght: false
      })
      return
    } else if (list.length <= 2) {
      this.setData({
        listLenght: false
      })
      list.splice(index, 1)
      // wx.showModal({
      //   cancelColor: 'cancelColor',
      // })
      this.setData({
        list: list
      })
    } else {
      list.splice(index, 1)
      // wx.showModal({
      //   cancelColor: 'cancelColor',
      // })
      this.setData({
        list: list
      })
    }

  },
  // 品名输入
  bindInput(e) {
    let index = e.currentTarget.dataset.index,
      list = this.data.list
    // console.log(e, 'pinming', list[index].selectProductname.length)
    list[index].productnamelength = (list[index].selectProductname.length + e.detail.cursor)
    if (list[index].selectProductname.length + e.detail.cursor > 25) {
      return
    } else {
      list[index].productnamevalue = e.detail.value
    }
    this.setData({
      list: list
    })
  },
  //品名推荐标签选择
  clickPmTag(e) {
    let index = e.currentTarget.dataset.index,
      index2 = e.currentTarget.dataset.index2,
      list = this.data.list,
      listI = list[index]

    if (list[index].productnameList[index2].ProductName.length + listI.productnamevalue.length > 25) {
      // list[index].productnamevalue.slice(25,(list[index].productnameList[index2].ProductName.length + listI.productnamevalue.length-25))
      wx.showToast({
        title: '不能超过25字,请简化输入的描述',
        icon: 'none'
      })
      return;
    } else {
      list[index].productnameListIndex = index2;
      list[index].productnamelength = (Number(list[index].productnamelength) - Number(list[index].selectProductname.length)) + Number(list[index].productnameList[index2].ProductName.length);
      list[index].selectProductname = list[index].productnameList[index2].ProductName;
      list[index].productnamemaxlength = 25 - Number(list[index].productnameList[index2].ProductName.length);
      // list[index].productnamemaxlength + list[index].selectProductname.length >= 25 ? 25 : list[index].productnamemaxlength + list[index].selectProductname.length
      // 25 - Number(list[index].productnameList[index2].ProductName.length);
      this.setData({
        list: list
      })
      this.queryGuigeType(this.data.classid, list[index].productnameList[index2].ProductName, index)
    }
  },
  //删除选中品名
  delselectProductname(e) {
    let index = e.currentTarget.dataset.index,
      list = this.data.list
    // console.log(list[index].productnamemaxlength + list[index].selectProductname.length)
    list[index].productnamelength = list[index].productnamelength - list[index].selectProductname.length
    list[index].productnamemaxlength = list[index].productnamemaxlength + list[index].selectProductname.length >= 25 ? 25 : list[index].productnamemaxlength + list[index].selectProductname.length
    list[index].selectProductname = ''
    list[index].productnameListIndex = -1
    this.setData({
      list
    })
  },
  // 规格输入
  bindInputSpecification(e) {
    let index = e.currentTarget.dataset.index,
      list = this.data.list
    list[index].specificationlength = (list[index].selectSpecification.length + e.detail.cursor)
    if (list[index].selectSpecification.length + e.detail.cursor > 25) {
      return
    } else {
      list[index].specificationvalue = e.detail.value
    }
    this.setData({
      list: list
    })
  },
  //规格推荐标签选择
  clickPmTagSpecification(e) {
    let index = e.currentTarget.dataset.index,
      index2 = e.currentTarget.dataset.index2,
      list = this.data.list
      if (list[index].specificationList[index2].Specification.length + list[index].specificationvalue.length > 25) {
        wx.showToast({
          title: '不能超过25字,请简化输入的描述',
          icon: 'none'
        })
        return;
      } else {
      list[index].specificationListIndex = index2;
      list[index].specificationlength = (Number(list[index].specificationlength) - Number(list[index].selectSpecification.length)) + Number(list[index].specificationList[index2].Specification.length);
      list[index].selectSpecification = list[index].specificationList[index2].Specification;

      list[index].specificationmaxlength = 25 - Number(list[index].specificationList[index2].Specification.length);
      this.setData({
        list: list
      })
    }


  },
  //删除选中规格
  delselectSpecification(e) {
    let index = e.currentTarget.dataset.index,
      list = this.data.list
    list[index].specificationlength = list[index].specificationlength - list[index].selectSpecification.length
    list[index].specificationmaxlength =  list[index].specificationmaxlength + list[index].selectSpecification.length >= 25 ? 25 : list[index].specificationmaxlength + list[index].selectSpecification.length
    // list[index].specificationmaxlength - Number(list[index].selectSpecification.length)
    list[index].selectSpecification = ''
    list[index].specificationListIndex = -1
    this.setData({
      list
    })
  },
  // 查询推荐品名
  queryPInmingBytype(classid, unit) {
    let that = this
    wx.showLoading({
      title: '数据加载中',
    })
    app.getDaoPost('api/FeijiuApp/Feijiu_BJ_Get_ProByClass', {
      classid
    }, r => {
      console.log(r, '推荐品名')
      wx.hideLoading({
        success: (res) => {},
      })
      let list = this.data.list,
        moude = this.data.moude,
        dataTempList = this.data.dataTempList
      moude.productnameList = r.data
      moude.unit = unit
      if (dataTempList.length > 0) {
        dataTempList.forEach(item => {
          let tempmoude = {}
          tempmoude.productnamevalue = that.getStr(item.productname, 1) //输入品名
          tempmoude.specificationvalue = that.getStr(item.specification, 1) //输入规格
          tempmoude.selectProductname = that.getStr(item.productname, 0) //选择推荐的品名
          tempmoude.selectSpecification = that.getStr(item.specification, 0) //选择推荐的规格
          if (that.getStr(item.productname, 0).length > 0 && that.getStr(item.productname, 1).length) {
            tempmoude.productnamelength = that.getStr(item.productname, 0).length + that.getStr(item.productname, 1).length //品名长度
          } else if (that.getStr(item.productname, 0).length > 0 && that.getStr(item.productname, 1).length <= 0) {
            tempmoude.productnamelength = that.getStr(item.productname, 0).length //品名长度
          } else if (that.getStr(item.productname, 0).length <= 0 && that.getStr(item.productname, 1).length > 0) {
            tempmoude.productnamelength = that.getStr(item.productname, 1).length //品名长度
          }
          if (that.getStr(item.specification, 0).length > 0 && that.getStr(item.specification, 1).length) {
            tempmoude.specificationlength = that.getStr(item.specification, 0).length + that.getStr(item.specification, 1).length //规格长度
          } else if (that.getStr(item.specification, 0).length > 0 && that.getStr(item.specification, 1).length <= 0) {
            tempmoude.specificationlength = that.getStr(item.specification, 0).length //规格长度
          } else if (that.getStr(item.specification, 0).length && that.getStr(item.specification, 1).length > 0) {
            tempmoude.specificationlength = that.getStr(item.specification, 1).length //规格长度
          }
          // tempmoude.specificationlength= that.getStr(item.specification,0).length + that.getStr(item.specification,1).length//规格长度
          tempmoude.productnamemaxlength = 25 - that.getStr(item.productname, 0).length, //输入最大长度
            tempmoude.specificationmaxlength = 25 - that.getStr(item.specification, 0).length, //输入最大长度
            tempmoude.productnameList = r.data, //品名推荐标签
            tempmoude.specificationList = [],
            tempmoude.productnameListIndex = -1, //选品名下表
            tempmoude.specificationListIndex = -1, //选规格下表
            tempmoude.maxprice = item.maxprice,
            tempmoude.minprice = item.minprice,
            tempmoude.unit = item.unit
          tempmoude.id = item.id
          list.push(tempmoude)
        })
        if (dataTempList.length > 1) {
          that.setData({
            listLenght: true
          })
        }
      } else {
        list.push(JSON.parse(JSON.stringify(moude)))
      }
      this.setData({
        list,
        moude
      })
    })
  },
  // 查询推荐规格
  queryGuigeType(classid, productname, index) {
    console.log(classid, productname, index)
    app.getDaoPost('api/FeijiuApp/Feijiu_BJ_Get_SpecByClassPro', {
      classid,
      productname
    }, r => {
      console.log(r, '推荐规格')
      let list = this.data.list
      list[index].specificationList = r.data
      this.setData({
        list
      })
    })
  },
  maxpriceInput(e) {
    let index = e.currentTarget.dataset.index,
      list = this.data.list
    list[index].maxprice = this.paseInt(e.detail.value)
    this.setData({
      list: list
    })
  },
  minpriceInput(e) {
    let index = e.currentTarget.dataset.index,
      list = this.data.list
    let price = this.paseInt(e.detail.value);
    list[index].minprice = price
    this.setData({
      list: list
    })
  },
  // 确定添加
  addBaojia(e) {
    let list = this.data.list,
      bjlist = [],
      goback = false
    // for (let i = 0; i < list.length; i++) {
    //   if (list[i].productnamelength == 0) {
    //     wx.showToast({
    //       title: '品名' + (i + 1) + '能为空',
    //       icon: 'none'
    //     })
    //     goback = false
    //     break;
    //   } else if (list[i].minprice == "") {
    //     wx.showToast({
    //       title: '品名' + (i + 1) + '最低价不能为空',
    //       icon: 'none'
    //     })
    //     goback = false
    //     break;
    //   } else if (list[i].maxprice == "") {
    //     wx.showToast({
    //       title: '品名' + (i + 1) + '最高价不能为空',
    //       icon: 'none'
    //     })
    //     goback = false
    //     break;
    //   } else {
    //     bjlist.push({
    //       id: list[i].id,
    //       productname: list[i].selectProductname + '&' + list[i].productnamevalue,
    //       specification: list[i].selectSpecification + '&' + list[i].specificationvalue,
    //       minprice: list[i].minprice,
    //       maxprice: list[i].maxprice,
    //       unit: list[i].unit
    //     })
    //   }
    // }

    try {
      list.forEach((item, index) => {
        if (item.productnamelength == 0) { //品名为空
          // console.log(index)
          wx.showToast({
            title: '品名' + (index + 1) + '不能为空',
            icon: 'none'
          })
          goback = false
          throw new Error(`品名${index + 1}不能为空`)
        } else if (item.minprice == '') { //最低价
          wx.showToast({
            title: `品名${index + 1}中最低价不能为空`,
            icon: 'none'
          })
          goback = false
          throw new Error(`品名${index + 1}中最低价不能为空`)
        } else if (item.maxprice == '') {
          wx.showToast({
            title: `品名${index + 1}中最高价不能为空`,
            icon: 'none'
          })
          goback = false
          throw new Error(`品名${index + 1}中最高价不能为空`)
        }else if(parseFloat(item.minprice)>parseFloat(item.maxprice)){
          wx.showToast({
            title: `品名${index + 1}中最低价不能高于最高价`,
            icon: 'none'
          })
          goback = false
          throw new Error(`品名${index + 1}中最低价不能高于最高价`)
        }
         else {
          goback = true
          bjlist.push({
            id: item.id,
            productname: item.selectProductname + '&' + item.productnamevalue,
            specification: item.selectSpecification + '&' + item.specificationvalue,
            minprice: item.minprice,
            maxprice: item.maxprice,
            unit: item.unit
          })
        }

      })
    } catch (e) {
      console.log(typeof (e))
      goback = false
    }

    if (goback == true) {
      let pages = getCurrentPages(); // 当前页的数据
      let prevPage = pages[pages.length - 2]; // 上一页的数据
      /** prevPageValue 是上一页你想被携带过去的数据 */
      prevPage.setData({
        bjlist: bjlist
      })
      wx.navigateBack({});
    }
  },
  getStr(str, type) {
    if (str.length > 0) {
      if (str.indexOf("&") != -1) {
        if (type == 0) {
          return str.substring(0, str.indexOf("&"));
        } else {
          return str.substring(str.indexOf("&") + 1, str.length)
        }
      } else {
        return ''
      }
    }
  },
  paseInt(val) {
    let price = val
    price = price.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
    price = price.replace(/\.{2}/g, ".")
    price = price.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".")
    price = price.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    if (price.indexOf(".") < 0 && price != "") {
      price = parseFloat(price)
    }
    return price
  }
})


